<template>
    <view class="my-page">
        <view class="header">
            <h2>我的</h2>
            <uni-icons type="mail-open" size="25" class="mail-icon" @click="mail"></uni-icons>
        </view>
        <view class="my-name" @click="updateusername">
            <!-- 修改为显示用户名 -->
            <h3 class="name">{{ userInfo.username || '未获取到用户名' }}</h3>
            <uni-icons type="compose" size="20" class="compose-icon" ></uni-icons>
        </view>
        <view class="my-baby">
            <!-- 只遍历年龄最小的两个宝宝 -->
            <button class="sign-button" v-for="baby in filteredBabyList" :key="baby.id">
                <text>{{ calculateAge(baby.birthday) }}&nbsp;{{ baby.gender === 1 ? '男宝' : '女宝' }}</text>
            </button>
        </view>
        <view class="my-first-option">
            <view class="my-option" @click="babymanage">
                <uni-icons type="person" size="40" class="contact-icon" color="#aaaaff"></uni-icons>
                <view class="my-option-name">&nbsp;&nbsp;宝宝管理</view>
                <uni-icons type="right" size="30" class="right-icon" color="#cccccc"></uni-icons>
            </view>
            <view class="my-option" @click="knowledge">
                <uni-icons type="calendar" size="40" class="contact-icon" color="#aaaaff"></uni-icons>
                <view class="my-option-name">&nbsp;&nbsp;知识收藏</view>
                <uni-icons type="right" size="30" class="right-icon" color="#cccccc"></uni-icons>
            </view>
            <view class="my-option" @click="recipe">
                <uni-icons type="wallet" size="40" class="contact-icon" color="#aaaaff"></uni-icons>
                <view class="my-option-name">&nbsp;&nbsp;菜谱收藏</view>
                <uni-icons type="right" size="30" class="right-icon" color="#cccccc"></uni-icons>
            </view>
        </view>

        <view class="my-first-option">
            <view class="my-option" @click="showShareActionSheet">
                <uni-icons type="staff" size="40" class="contact-icon" color="#aaaaff"></uni-icons>
                <view class="my-option-name">&nbsp;&nbsp;推荐给好友</view>
                <uni-icons type="right" size="30" class="right-icon" color="#cccccc"></uni-icons>
            </view>
        </view>

        <view class="my-first-option">
            <view class="my-option" @click="about">
                <uni-icons type="phone" size="40" class="contact-icon" color="#aaaaff"></uni-icons>
                <view class="my-option-name">&nbsp;&nbsp;关于康宝宝</view>
                <uni-icons type="right" size="30" class="right-icon" color="#cccccc"></uni-icons>
            </view>
            <view class="my-option" @click="setup">
                <uni-icons type="gear" size="40" class="contact-icon" color="#aaaaff"></uni-icons>
                <view class="my-option-name">&nbsp;&nbsp;设置</view>
                <uni-icons type="right" size="30" class="right-icon" color="#cccccc"></uni-icons>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';

// 用户信息和宝宝列表
const userInfo = ref({});
const babyList = ref([]);
// 过滤后的宝宝列表，只包含年龄最小的两个宝宝
const filteredBabyList = ref([]);

// 获取用户信息
const fetchUserInfo = async () => {
    try {
        const userId = uni.getStorageSync('userId'); // 假设从本地存储获取用户 ID
        const res = await uni.request({
            method: 'GET',
            url: `http://localhost:9100/api/user/selectById?id=${userId}`,
            header: {
                'bece_token': uni.getStorageSync('bece_token')
            }
        });
        if (res.data.code === 200) {
            userInfo.value = res.data.data;
        } else {
            uni.showToast({
                title: res.data.msg || '获取用户信息失败',
                duration: 2000
            });
        }
    } catch (error) {
        uni.showToast({
            title: '网络请求失败',
            icon: 'none',
            duration: 2000
        });
        console.error('请求出错:', error);
    }
};

// 获取用户信息和宝宝列表
const fetchBabyList = async () => {
    uni.request({
        method: 'GET',
        url: 'http://localhost:9100/api/baby/selectList',
        header: {
            'bece_token': uni.getStorageSync('bece_token')
        },
        success: (res) => {
            console.log(res.data);
            if (res.data.code == 200) {
                babyList.value = res.data.data;
                // 筛选出年龄最小的两个宝宝
                filterBabyList();
            } else {
                uni.showToast({
                    title: res.data.msg,
                    duration: 2000
                });
            }
        }
    });
};

// 筛选年龄最小的两个宝宝
const filterBabyList = () => {
    // 根据宝宝生日进行排序，生日越近年龄越小
    const sortedBabyList = babyList.value.sort((a, b) => {
        return new Date(b.birthday) - new Date(a.birthday);
    });
    // 取前两个宝宝
    filteredBabyList.value = sortedBabyList.slice(0, 2);
};

// 计算宝宝年龄
const calculateAge = (birthday) => {
    if (!birthday) return '';

    const birth = new Date(birthday);
    const now = new Date();

    let months = (now.getFullYear() - birth.getFullYear()) * 12;
    months += now.getMonth() - birth.getMonth();

    if (months < 12) {
        return `${months}个月`;
    } else {
        const years = Math.floor(months / 12);
        const remainingMonths = months % 12;
        return remainingMonths > 0 ?
            `${years}岁${remainingMonths}个月` :
            `${years}岁`;
    }
};

// 跳转到宝宝管理页面
const babymanage = () => {
    uni.redirectTo({
        url: '/pages/baby/list/list',
    });
};

const about = () => {
    uni.redirectTo({
        url: '/pages/user/about/about',
    });
};

const setup = () => {
    uni.redirectTo({
        url: '/pages/setting/setting/setting',
    });
};

const mail = () => {
    uni.redirectTo({
        url: '/pages/user/message/message',
    });
};

const updateusername = () => {
    uni.redirectTo({
        url: '/pages/user/updatenickname/updatenickname',
    });
};

const knowledge = () => {
    uni.redirectTo({
        url: '/pages/user/collect_knowledge/collect_knowledge',
    });
};

const recipe = () => {
    uni.redirectTo({
        url: '/pages/user/collect_recipe/collect_recipe',
    });
};


// 显示分享操作菜单
const showShareActionSheet = () => {
    uni.showActionSheet({
        itemList: ['分享到微信', '分享到QQ', '分享到微博'],
        success: (res) => {
            const sharePlatforms = ['weixin', 'qq', 'sinaweibo'];
            const platform = sharePlatforms[res.tapIndex];

            // 调用分享功能
            uni.share({
                provider: platform,
                type: 0, // 0: 文字, 1: 图片, 2: 链接
                title: '推荐康宝宝给你',
                summary: '快来使用康宝宝，记录宝宝的成长吧！',
                href: 'https://www.kangbaobao.com', // 分享链接
                success: () => {
                    uni.showToast({
                        title: '分享成功',
                        icon: 'success'
                    });
                },
                fail: (err) => {
                    uni.showToast({
                        title: '分享失败',
                        icon: 'none'
                    });
                    console.error('分享失败:', err);
                }
            });
        },
        fail: (err) => {
            console.error('操作菜单失败:', err);
        }
    });
};

// 页面加载时获取数据
onMounted(() => {
    fetchUserInfo();
    fetchBabyList();
});
</script>

<style scoped>
.my-page {
    background-image: linear-gradient(to bottom, #d9d9d9, #fff);
}

.header {
    display: flex;
    justify-content: space-between;
    padding: 18rpx 20rpx;
}

.my-name {
    display: flex;
    justify-content: flex-start;
    margin-top: 48rpx;
    margin-left: 30rpx;
    margin-bottom: 35rpx;
}

.compose-icon {}

.my-baby {
    display: flex;
    justify-content: flex-start;
    margin-left: 30rpx;
    margin-bottom: 68rpx;
}

.my-first-option {
    box-shadow: 0rpx 0rpx 4rpx rgb(170, 170, 127);
    margin: 30rpx 30rpx;
    background-color: #fff;
    border-radius: 10rpx;
}

.my-option {
    display: flex;
    justify-content: flex-start;
    padding: 20rpx 0 20rpx 20rpx;
    border-bottom: 4rpx solid #f2f2f2;
}

.my-option-name {
    font-size: 33rpx;
    display: flex;
    align-items: center;
}

.right-icon {
    margin-left: auto;
    display: flex;
    align-items: center;
}

.sign-button {
    width: 100px;
    height: 30px;
    line-height: 60rpx;
    font-size: 14px;
    background-color: #ffffff;
    border-color: #fff;
    border-radius: 50rpx;
    margin: 0;
    padding: 0;
}
</style>